﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Netfraction.Network.Protocol.BASE.Handler
{
    public class HandlerQUI : ProtocolMessageActionHandler
    {
        public HandlerQUI()
            : base()
        {
            mSupportedConnectionStates = new List<RemoteMachine.ConnectionState>();
        }

        #region ProtocolMessageActionHandler Members

        public override string ProtocolActionCode
        {
            get { return "QUI"; }
        }

        public override bool HandleProtocolMessage(Netfraction.RemoteMachine.Node node, ProtocolMessage message, IEnumerable<ProtocolFeature> extenders)
        {
            if (node is RemoteMachine.Hub)
            {
                //Console.WriteLine("in QUI handler");
                //message.GETParameterOptions = DecodeParameters(message.GETParameterOptions);
                //(node as RemoteMachine.Hub).SessionId = message.GETParameterOptions[0].ParameterValue;
                //Console.WriteLine("Disconnecting SID: {0}", message.GETParameterOptions[0].ParameterValue);
                LocalMachine.Client client = LocalMachine.Client.GetInstance();
                lock (client)
                {
                    /*var shareSizes = client.Peers.Select(mC => mC.Value.Identity.ShareSize);
                    double shareTotal = 0;
                    foreach (long ss in shareSizes)
                    {
                        shareTotal += ss;
                    }
                    System.Diagnostics.Debug.WriteLine(String.Format("Total hub share is {0} gigabytes.", Math.Round(shareTotal / 1024 / 1024 / 1024, 2)));*/
                    var disc = client.Peers.Where(c => c.SessionId == message.Parameters[0].ParameterValue);
                    if (disc.Count() > 0)
                    {
                        RemoteMachine.Peer p = disc.First();
                        //p.IsOnline = false;
                        //System.Diagnostics.Debug.WriteLine(String.Format("*** Parts: {0}", p.Identity.Nickname));
                        client.Peers.Remove(p.Identity.ClientId);
                    }
                }

                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion
    }
}
